using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.WorkOrder;
using B.S.XZYData.Api.Read.Dto.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.WorkOrder
{
    /// <summary>
    /// 获取工单分页列表处理器
    /// </summary>
    public class GetWorkOrderPageHandler : IRequestHandler<GetWorkOrderPageCommand, ApiPageing<WorkOrderDto>>
    {
        private readonly IBaseRepository<WorkOrderModel> _workOrderRepo;
        private readonly IBaseRepository<WorkOrderProcessModel> _workOrderProcessRepo;
        private readonly IMapper _mapper;

        public GetWorkOrderPageHandler(
            IBaseRepository<WorkOrderModel> workOrderRepo,
            IBaseRepository<WorkOrderProcessModel> workOrderProcessRepo,
            IMapper mapper)
        {
            _workOrderRepo = workOrderRepo;
            _workOrderProcessRepo = workOrderProcessRepo;
            _mapper = mapper;
        }

        public async Task<ApiPageing<WorkOrderDto>> Handle(GetWorkOrderPageCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<WorkOrderDto>();

            try
            {
                // 构建查询条件
                var query = _workOrderRepo.GetAll();

                // 工单编号模糊查询
                if (!string.IsNullOrWhiteSpace(request.WorkOrderCode))
                {
                    query = query.Where(x => x.Code.Contains(request.WorkOrderCode));
                }

                // 产品编号模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProductCode))
                {
                    query = query.Where(x => x.ProductCode != null && x.ProductCode.Contains(request.ProductCode));
                }

                // 产品名称模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProductName))
                {
                    query = query.Where(x => x.ProductName != null && x.ProductName.Contains(request.ProductName));
                }

                // 产品规格模糊查询
                if (!string.IsNullOrWhiteSpace(request.Spec))
                {
                    query = query.Where(x => x.Spec != null && x.Spec.Contains(request.Spec));
                }

                // 单位查询
                if (!string.IsNullOrWhiteSpace(request.Unit))
                {
                    query = query.Where(x => x.Unit == request.Unit);
                }

                // 实际数量查询
                if (request.ActualQuantity.HasValue)
                {
                    query = query.Where(x => x.ActualQuantity == request.ActualQuantity);
                }

                // 状态查询
                if (!string.IsNullOrWhiteSpace(request.Status))
                {
                    query = query.Where(x => x.Status == request.Status);
                }

                // 计划开始时间范围查询
                if (request.PlannedStartTimeStart.HasValue)
                {
                    query = query.Where(x => x.PlannedStartTime >= request.PlannedStartTimeStart);
                }
                if (request.PlannedStartTimeEnd.HasValue)
                {
                    query = query.Where(x => x.PlannedStartTime <= request.PlannedStartTimeEnd);
                }

                // 计划结束时间范围查询
                if (request.PlannedEndTimeStart.HasValue)
                {
                    query = query.Where(x => x.PlannedEndTime >= request.PlannedEndTimeStart);
                }
                if (request.PlannedEndTimeEnd.HasValue)
                {
                    query = query.Where(x => x.PlannedEndTime <= request.PlannedEndTimeEnd);
                }

                // 实际开始时间范围查询
                if (request.ActualStartTimeStart.HasValue)
                {
                    query = query.Where(x => x.ActualStartTime >= request.ActualStartTimeStart);
                }
                if (request.ActualStartTimeEnd.HasValue)
                {
                    query = query.Where(x => x.ActualStartTime <= request.ActualStartTimeEnd);
                }

                // 实际结束时间范围查询
                if (request.ActualEndTimeStart.HasValue)
                {
                    query = query.Where(x => x.ActualEndTime >= request.ActualEndTimeStart);
                }
                if (request.ActualEndTimeEnd.HasValue)
                {
                    query = query.Where(x => x.ActualEndTime <= request.ActualEndTimeEnd);
                }

                // 创建时间范围查询
                if (request.CreateTimeStart.HasValue)
                {
                    query = query.Where(x => x.CreateTime >= request.CreateTimeStart);
                }
                if (request.CreateTimeEnd.HasValue)
                {
                    query = query.Where(x => x.CreateTime <= request.CreateTimeEnd);
                }

                // 创建人查询
                if (!string.IsNullOrWhiteSpace(request.CreateBy))
                {
                    query = query.Where(x => x.CreateBy != null && x.CreateBy.Contains(request.CreateBy));
                }

                // 排序（按创建时间倒序）
                query = query.OrderByDescending(x => x.CreateTime);

                // 获取总数
                var totalCount = query.Count();

                // 分页
                var workOrders = query
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                // 映射到DTO
                var workOrderDtos = _mapper.Map<List<WorkOrderDto>>(workOrders);

                // 统计每个工单的工序数量
                foreach (var workOrderDto in workOrderDtos)
                {
                    workOrderDto.ProcessCount = _workOrderProcessRepo.GetAll()
                        .Where(x => x.WorkOrderId == workOrderDto.Id)
                        .Count();
                }

                res.PageData = workOrderDtos;
                res.TotaCount = totalCount;
                res.TotaPage = (int)Math.Ceiling((double)totalCount / request.Size);
                res.Code = ApiEnum.Success;
                res.Msg = "获取工单列表成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取工单列表失败：{ex.Message}";
            }

            return res;
        }
    }
}
